{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# nqueens_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/sat/nqueens_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/sat/samples/nqueens_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "OR-Tools solution to the N-queens problem."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import time\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "\n",
    "class NQueenSolutionPrinter(cp_model.CpSolverSolutionCallback):\n",
    "    \"\"\"Print intermediate solutions.\"\"\"\n",
    "\n",
    "    def __init__(self, queens: list[cp_model.IntVar]):\n",
    "        cp_model.CpSolverSolutionCallback.__init__(self)\n",
    "        self.__queens = queens\n",
    "        self.__solution_count = 0\n",
    "        self.__start_time = time.time()\n",
    "\n",
    "    @property\n",
    "    def solution_count(self) -> int:\n",
    "        return self.__solution_count\n",
    "\n",
    "    def on_solution_callback(self):\n",
    "        current_time = time.time()\n",
    "        print(\n",
    "            f\"Solution {self.__solution_count}, \"\n",
    "            f\"time = {current_time - self.__start_time} s\"\n",
    "        )\n",
    "        self.__solution_count += 1\n",
    "\n",
    "        all_queens = range(len(self.__queens))\n",
    "        for i in all_queens:\n",
    "            for j in all_queens:\n",
    "                if self.value(self.__queens[j]) == i:\n",
    "                    # There is a queen in column j, row i.\n",
    "                    print(\"Q\", end=\" \")\n",
    "                else:\n",
    "                    print(\"_\", end=\" \")\n",
    "            print()\n",
    "        print()\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "def main(board_size: int) -> None:\n",
    "    # Creates the solver.\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # Creates the variables.\n",
    "    # There are `board_size` number of variables, one for a queen in each column\n",
    "    # of the board. The value of each variable is the row that the queen is in.\n",
    "    queens = [model.new_int_var(0, board_size - 1, f\"x_{i}\") for i in range(board_size)]\n",
    "\n",
    "    # Creates the constraints.\n",
    "    # All rows must be different.\n",
    "    model.add_all_different(queens)\n",
    "\n",
    "    # No two queens can be on the same diagonal.\n",
    "    model.add_all_different(queens[i] + i for i in range(board_size))\n",
    "    model.add_all_different(queens[i] - i for i in range(board_size))\n",
    "\n",
    "    # Solve the model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    solution_printer = NQueenSolutionPrinter(queens)\n",
    "    solver.parameters.enumerate_all_solutions = True\n",
    "    solver.solve(model, solution_printer)\n",
    "\n",
    "    # Statistics.\n",
    "    print(\"\\nStatistics\")\n",
    "    print(f\"  conflicts      : {solver.num_conflicts}\")\n",
    "    print(f\"  branches       : {solver.num_branches}\")\n",
    "    print(f\"  wall time      : {solver.wall_time} s\")\n",
    "    print(f\"  solutions found: {solution_printer.solution_count}\")\n",
    "\n",
    "\n",
    "# By default, solve the 8x8 problem.\n",
    "size = 8\n",
    "if len(sys.argv) > 1:\n",
    "    size = int(sys.argv[1])\n",
    "main(size)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
